<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\common\library\Auth;
use think\Config;
use fast\Http;
use app\admin\model\Cangku;
use think\Loader;
/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $cangku_model;
    protected $auth_array;
    protected $role;
    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        $this->cangku_model = new Cangku();
        
        $group_id = Db::name('auth_group_access')->where('uid',$this->auth->id)->value('group_id');
        $auth_id = Db::name('auth_group')->where('id',$group_id)->field('rules,name')->find();
        $this->role = $auth_id['name'];
        if($auth_id['rules']=='*'){
          $this->auth_array = '*';
        }else{
          $this->auth_array = explode(',', $auth_id['rules']);
        }

    }  
    /**
     * 获取渠道来源channel和类别type、客户名称client
     */
    public function get_common_list(){

        $data = [];
        $data['channel'] = array_keys(Config('site.channel'));
        $data['type'] = array_keys(Config('site.type'));
        $data['client'] = array_keys(Config('site.client'));
        $this->success('返回成功',$data);
    }

     /**
     * 仓库列表
     * @ApiSummary  ()
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/index/cangku_list)
     * @ApiReturn ({
      {
  "code": 1,
  "msg": "仓库列表",
  "time": "1602400559",
  "data": [
    {
      "id": 2,
      "name": "仓库2",
      "status": "1",
      "createtime": 1601440190,
      "weigh": 2,
      "status_text": "在售"
    },
    {
      "id": 1,
      "name": "仓库1",
      "status": "1",
      "createtime": 1601440093,
      "weigh": 1,
      "status_text": "在售"
    }
  ]
}

     })
     */
    public function cangku_list(){
        // 仓库查看权限为 252
        if($this->auth_array!=='*'){
          if(!in_array(252, $this->auth_array))$this->error('抱歉，你没有该权限');
        }
        
        $cangku_id = $this->auth->cangku_ids;
        $cangku_list = $this->cangku_model->where('id','in',$cangku_id)->order('weigh desc')->select();
        $this->success('仓库列表',$cangku_list);
    }

     /**
     * 商品入库
     * @param array $good_json [{"name":"商品名称","location":"位置","num":"12","batch_number":"批号","in_num":"3","not_in_num":"3","type":"品类（从接口获取）","channel_source":"渠道来源（从接口获取）","cangku_id":"仓库id","codebar":"条形码","huohao":"货号","mianshui":"免税编号","zhekou":"折扣"}]
     */
    public function in_cangku(){
        // if($this->auth_array!=='*'){
        //   // 权限为 265
        //   if(!in_array(265, $this->auth_array))$this->error('抱歉，你没有该入库权限');
        // }
        $param = input();

        $warehousing = new \app\admin\model\Warehousing;

        $param['user_id'] = $this->user_id;
        $param['good_json'] = json_encode($param['good_json']);
        $result = $warehousing->save($param);
        if ($result === false) {
            $this->error($warehousing->getError());
        }else{
            $this->success('商品入库成功');
        }
    }

       /**
     * 仓库的商品列表
     * @ApiSummary  ()
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/index/cangku_goods)
     * @ApiParams   (name="cangku_id", type="int", required=true, description="仓库id")
     * @ApiReturn ({
{
  "code": 1,
  "msg": "仓库的商品列表",
  "time": "1604050267",
  "data": [
    {
      "id": 3,
      "sku": "商品名称",
      "in_num": 13,
      "not_in_num": 5,
      "shengyu_num": 11,
      "out_num": 1,
      "cangku_id": 2,
      "damage_num": 1,
      "return_num": 1,
      "createtime": 1604029058,
      "batch_number": null,
      "location": null,
      "rugood_id": 3,
      "name": "仓库2",
      "status": "1"
    }
  ]
}
     })
     */
     public function cangku_goods(){
      if($this->auth_array!=='*'){
          // 查看入库商品为 264
        if(!in_array(264, $this->auth_array))$this->error('抱歉，你没有该查看商品权限');
      }
        $rugood = new \app\admin\model\Rugood;
        $list = $rugood
            ->field('*,id as rugood_id')
            ->with('cangku')
            ->where('cangku_id',input('cangku_id'))
            ->select();
        $list = collection($list)->toArray();
      
        $this->success('仓库的商品列表',$list);
     }

       /**
     * 商品出库 (要么添加成功code为1，要么报什么什么商品库存不足code为0)
     * @ApiSummary  (商品名称从从仓库的商品列表接口获取)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/out_cangku)
     * @ApiParams   (name="good_json", type="array", required=true, description="{'rugood_id':'商品id,从商品列表获取','out_num':'出货数量','client':'客户从接口获取'}")
     * @ApiParams   (name="outtime", type="int", required=true, description="出货时间->时间戳")
     * @ApiReturn ({
{
    "code": 0,
    "msg": "商品名称库存不足",
    "time": "1604300478",
    "data": null
}
     })
     */

    public function out_cangku(){
        if($this->auth_array!=='*'){
          // 查看商品出库为 271
          if(!in_array(271, $this->auth_array))$this->error('抱歉，你没有该商品出库权限');
        }
        $param = input();
        foreach ($param['good_json'] as $key => $value) {
            $rugood_data = Db::name('rugood')->where('id',$value['rugood_id'])->find();
            if($rugood_data['shengyu_num']<$value['out_num'])$this->error($rugood_data['sku'].'库存不足');
        }

        $param['good_json'] = json_encode($param['good_json']);
        $out_cangku = new \app\admin\model\Out;

        $param['user_id'] = $this->user_id;

        $result = $out_cangku->save($param);
        if ($result === false) {
            $this->error($out_cangku->getError());
        }else{
            $this->success('商品出库成功');
        }
    }
    /**
     * 商品破损上报
     * @ApiSummary  (商品名称从从仓库的商品列表接口获取)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/posun_cangku)
     * @ApiParams   (name="good_json", type="array", required=true,  sample="{'rugood_id':'商品id,从商品列表获取','damage_num':'破损数量'}")
     * @ApiReturn ({

     })
     */
    public function posun_cangku(){
        if($this->auth_array!=='*'){
         // 商品破损上报 277
          if(!in_array(277, $this->auth_array))$this->error('抱歉，你没有该商品破损上报权限');
        }
        $param = input();
     
        $posun_cangku = new \app\admin\model\Damage;

        $param['user_id'] = $this->user_id;
        $param['good_json'] = json_encode($param['good_json']);

        $result = $posun_cangku->save($param);
        // halt($param);
        if ($result === false) {
            $this->error($posun_cangku->getError());
        }else{
            $this->success('商品破损上报成功');
        }
    }

     /**
     * 商品退换货上报 (要么添加成功code为1，要么报什么什么商品库存不足code为0)
     * @ApiSummary  (商品名称从从仓库的商品列表接口获取)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/return_cangku)
     * @ApiParams   (name="good_json",type="array",required=true,description="{'rugood_id':'商品id,从商品列表获取','return_num':'退换数量','client':'客户从接口获取'}")
     * @ApiReturn ({
{
    "code": 0,
    "msg": "商品名称库存不足",
    "time": "1604300478",
    "data": null
}
     })
     */

    public function return_cangku(){
        if($this->auth_array!=='*'){
          // 商品退换货上报 283
          if(!in_array(283, $this->auth_array))$this->error('抱歉，你没有该商品退换货上报权限');
        }
        
        $param = input();
        foreach ($param['good_json'] as $key => $value) {
            $rugood_data = Db::name('rugood')->where('id',$value['rugood_id'])->find();
            if($rugood_data['shengyu_num']<$value['return_num'])$this->error($rugood_data['sku'].'库存不足');
        }

        $return_cangku = new \app\admin\model\Returned;

        $param['user_id'] = $this->user_id;
        $param['good_json'] = json_encode($param['good_json']);

        $result = $return_cangku->save($param);
        if ($result === false) {
            $this->error($return_cangku->getError());
        }else{
            $this->success('商品退换货上报成功');
        }
    }
     /**
     * 客户订货上传 (要么添加成功code为1，要么报什么什么商品库存不足code为0)
     * @ApiSummary  (商品名称从从仓库的商品列表接口获取)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/index/dinghuo)
     * @ApiParams   (name="good_json",type="array",required=true,description="{'name':'商品名称','unit_price'':'100','after_unit_price':'折后单价','origin_total_price':'原总价','after_total_price':'折后总价','ding_num':'订货数量','yifahuo':'已发货数量','weifahuo':'未发货数量','codebar':'条形码','huohao':'货号','mianshui':'免税编号','zhekou':
     '折扣','laiyuan':'渠道来源','pihao':'批号'}")
     * @ApiParams   (name="client",type="string",required=true,sample="客户名称从接口获取")
     * @ApiParams   (name="client_phone",type="string",required=true,sample="客户电话")
     * @ApiParams   (name="client_address",type="string",required=true,sample="客户地址")
     * @ApiParams   (name="dingtime",type="string",required=true,sample="订货日期时间戳格式")
     * @ApiParams   (name="pay_status",type="string",required=true,sample="支付状态:10=未支付,20=已支付,30=非全款支付")
     * @ApiParams   (name="shengyu",type="decimal",required=false,sample="如果选择了非全款支付，需要填入剩余尾款")
     * @ApiReturn ({
     })
     */

    public function dinghuo(){
        // if($this->auth_array!=='*'){
        //   // 客户订货上传 289
        //   if(!in_array(289, $this->auth_array))$this->error('抱歉，你没有该客户订货上传权限');
        // }
        $param = input();
      
        $dinghuo = new \app\admin\model\Dinghuo;
        
        $param['good_json'] = json_encode($param['good_json']);
        $param['user_id'] = $this->user_id;

        $result = $dinghuo->save($param);
        if ($result === false) {
            $this->error($dinghuo->getError());
        }else{
            $this->success('客户订货上传成功');
        }
    }

     /**
     * 客户供货单上传
     * @param longtext $good_json 商品数据如上一个订货接口,另外还有一个新字段本次发货数量:now_fahuo_num
     * @param string $client_phone 客户电话
     * @param string $client 客户名称（从接口获取）
     * @param string $client_address 客户地址
     */
    public function gong(){
        // if($this->auth_array!=='*'){
        //   // 商品退换货上报 301
        //   if(!in_array(301, $this->auth_array))$this->error('抱歉，你没有客户供货单上传权限');
        // }

        $param = input();
        $param['good_json'] = json_encode($param['good_json']);
        
        $gonghuo = new \app\admin\model\Gonghuo;

        $param['user_id'] = $this->user_id;

        $result = $gonghuo->save($param);
        if ($result === false) {
            $this->error($gonghuo->getError());
        }else{
            $this->success('客户供货单上传成功');
        }
    }
       /**
     * 物品搜索
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/index/search)
     * @ApiParams   (name="name", type="string", required=true, description="物品名称")
     * @ApiReturn ({
{
  "code": 1,
  "msg": "搜索结果",
  "time": "1604370390",
  "data": [
    {
      "id": 4,
      "sku": "商品名称",
      "cangku_id": 2,
      "in_num": 12,
      "not_in_num": 3,
      "shengyu_num": 10,
      "out_num": 1,
      "damage_num": 2,
      "return_num": 1,
      "batch_number": "批号",
      "location": "位置",
      "type": "口红",
      "channel_source": "渠道来源",
      "createtime": 1604303299,
      "name": "仓库2",
      "status": "1"//仓库状态:1=空闲,2=已满,3=已占用
    }
  ]
}
     })
     */
    public function search()
    {
        $cangku_ids = $this->auth->cangku_ids;

        $name = input('name');
        $Rugood = new \app\admin\model\Rugood;
        $res = $Rugood->with(['cangku'])->where(['sku'=>['like',"%$name%"]])->where('cangku_id','in',$cangku_ids)->select();

        $this->success('搜索结果',$res);
    }
    /**
     * 订单列表 status仓库状态:1=空闲,2=已满,3=已占用
     */
    public function order_list(){
        $warehousing = new \app\admin\model\Warehousing;
        $out_cangku = new \app\admin\model\Out;
        $posun_cangku = new \app\admin\model\Damage;
        $return_cangku = new \app\admin\model\Returned;

        $return['role'] = $this->role;
        $return['ruku'] = $warehousing->with([ 'admin'])->where('user_id',$this->user_id)->order('createtime desc')->select();
        $return['out'] = $out_cangku->with(['admin'])->where('user_id',$this->user_id)->order('createtime desc')->select();
        $return['posun'] = $posun_cangku->with(['admin'])->where('user_id',$this->user_id)->order('createtime desc')->select();
        $return['return'] = $return_cangku->with(['admin'])->where('user_id',$this->user_id)->order('createtime desc')->select();
        $this->success('订单列表',$return);
    }
    /**
     * 订货供货列表
     */
    public function dinghuo_list(){
        $Dinghuo = new \app\admin\model\Dinghuo;
        $Gonghuo = new \app\admin\model\Gonghuo;

        $return['role'] = $this->role;
        $return['dinghuo'] = $Dinghuo->where('user_id',$this->user_id)->order('createtime desc')->select();
        $return['gonghuo'] = $Gonghuo->where('user_id',$this->user_id)->order('createtime desc')->select();
        $this->success('订货供货列表',$return);
    }
}
